package com.gxitsky.plugin.servlet3;

import javax.servlet.AsyncContext;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author gxing
 * @desc TODO
 * @date 2022/1/6
 */
public class AsyncRequestProcess implements Runnable {

    private AsyncContext asyncContext;
    private int time;

    public AsyncRequestProcess() {
    }

    public AsyncRequestProcess(AsyncContext asyncContext, int time) {
        this.asyncContext = asyncContext;
        this.time = time;
    }

    @Override
    public void run() {
        System.out.println("是否异步:" + asyncContext.getRequest().isAsyncStarted());
        longProcessing(time);
        try {
            PrintWriter out = asyncContext.getResponse().getWriter();
            out.write("处理完成:" + time + " s!");
        } catch (IOException e) {
            e.printStackTrace();
        }
        asyncContext.complete();
    }

    private void longProcessing(int time) {

        try {
            Thread.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
